package model;

/**
 * An array of players for use in the game.
 * @author Group 20
 *
 */
public class Players 
{	
	int activePlayerIndex = 0;
	
	Player[] players;
	
    /**
     * Constructor, adds the value for number of players.
     * @param numberOfPlayers: number of players
     */
	public Players(int numberOfPlayers)
	{
		this.players = new Player[numberOfPlayers];
	}
	
	/**
	 * Getter, returns the array of players.
	 * @return players: array of players
	 */
	public Player[] getPlayers() 
	{
		return players;
	}


	/**
	 *  Add player on second-last position in players[]
	 * @param name: Player name
	 * @param color: Player color
	 * @param playerNumber: Player number
	 */
	public void addPlayer(String name, int color, int playerNumber)
	{
		for(int i = 0; i < players.length; i++)
		{
			if(players[i] == null)
			{
				players[i] = new Player(name, color, playerNumber);
				break;
			}
		}
	}
	
	/**
	 * Getter, returns the last player in the array.
	 * @return object of type Player
	 */
	public Player getLastPlayer()
	{
		return players[players.length-1];
	}
	
	/**
	 * Getter, gets next active player.
	 * @return object of type Player
	 */
	public Player getNextActivePlayer()
	{	
		while(true)
		{
			if (activePlayerIndex == players.length)
			{
				activePlayerIndex = 0;
			}
			else if(players[activePlayerIndex] != null)
			{
				Player activePlayer = players[activePlayerIndex];
				activePlayerIndex++;
				return activePlayer;
			}
			else
			{
				activePlayerIndex++;
			}
		}
	}
	
	/**
	 * Getter, returns the number of active players.
	 * @return numOfPlayers: number of players
	 */
	public int getNumOfPlayers()
	{
		int numOfPlayers = 0;
		for(int i = 0; i < players.length; i++)
		{
			if(players[i] != null)
				numOfPlayers++;
		}
		return numOfPlayers;
	}
	
	/**
	 * Remove player object from the arraylist and decrement point. If the removed player is first in line then skip the decrement
	 * @param player: object of type Player
	 */ 
	public void removePlayer(Player player)
	{		
		for (int i = 0; i < players.length; i++)
		{
			if (players[i] == player)
			{
				players[i] = null;
				break;
			}
		}
	}
	
	/**
	 * Returns the winner, he who has the highest score.
	 * @return player or null
	 */
	public Player getWinner()
	{
		for(int i = 0; i < players.length; i++)
		{
			if(players[i] != null)
				return players[i];
		}
		return null;
	}

	/**
	 * To string method.
	 */
	@Override
	public String toString() {
		return "Players [activePlayerIndex=" + activePlayerIndex + ", players="
				+ players + "]";
	}	
}